/**
 * Created by chris on 2017/5/22.
 */
import {Injectable} from '@angular/core';
import io from 'socket.io-client';

@Injectable()
export class SocketService {

    private socketUrlArr = ['https://app6.fx168api.com:9091', 'https://app7.fx168api.com:9091'];
    private index_socket: number = 0;
    private socketUrl: string = null;
    private remoteSocket;

    constructor() {
        this.index_socket = Math.floor((Math.random() * this.socketUrlArr.length));
        this.socketUrl = this.socketUrlArr[this.index_socket];
        console.log('SocketService index_socket:', this.index_socket, 'socketUrl:', this.socketUrl);
    }

    public connectRemoteServer(callback: any) {
        this.remoteSocket = this.initConnect();
        this.listenRemoteServer((key, data) => {
            callback(key, data);
        });
        this.remoteSocket.on('disconnect', () => {
            this.initConnect();
            this.listenRemoteServer((key, data) => {
                callback(key, data);
            });
        });
    }

    public listenRemoteServer(callback: any) {
        if (this.remoteSocket) {
            this.remoteSocket.on('quotationPushH5', data => {
                console.log('quotationPushH5:', data);
                let resArr = JSON.parse(data);
                for (let key in resArr) {
                    callback(key, resArr[key]);
                }
            });
        }
    }

    private initConnect() {
        let remoteSocket = io.connect(this.socketUrl, {reconnect: true});
        remoteSocket.on('connect', (data) => {
            console.log('connect:', data);
            remoteSocket.emit('quotationH5', {secret: "h5Socket", appType: "h5"});
        });

        return remoteSocket;
    }
}
